package a.miracle.androidlib.act

import a.miracle.androidlib.R
import a.miracle.androidlib.base.BaseAct
import a.miracle.androidlib.base.RBaseAdapter
import a.miracle.androidlib.base.RViewHolder
import a.miracle.androidlib.utils.ToastUtils
import a.miracle.lib_utils.DisplayUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SPUtils
import kotlinx.android.synthetic.main.act_layout_test.*
import kotlinx.android.synthetic.main.v_toolbar.*
import java.util.*

/**
 * @author A Miracle
 * @description:
 * @date :2021/11/20
 */
class LayoutTestAct : BaseAct() {

    override fun getLayoutId(): Int {
        return R.layout.act_layout_test
    }

    override fun onAfterSetContentLayout(savedInstanceState: Bundle?) {
        tv_title.text = "LayoutTest"
        iv_back.setOnClickListener { finish() }

        initRecyclerView()

        rv_content.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager = rv_content.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    val lastPos = layoutManager.findLastVisibleItemPosition()
                    tv_last_pos.text = "${lastPos / 2}"
                }
            }
        })

        // pos = index * 2
        bt_go.setOnClickListener {
            val position = et_position.text.toString().trim()
            if (position.isNotEmpty()){
                val pos = position.toInt() * 2
                if (pos < 0 || pos >= mAdapter.data.size) {
                    ToastUtils.show("pos scope [0, ${mAdapter.data.size / 2 - 1}]")
                } else {
                    rv_content.scrollToPosition(pos)
                }
            }
        }

        val delList = LinkedHashSet<Int>()

        val delStr = SPUtils.getInstance().getString("layout_test")
        val split = delStr.split(",")
        for (s in split) {
            if (s.isNotEmpty()) {
                delList.add(s.toInt())
            }
        }

        showDescAndRefresh(delList)

        //(index)
        bt_del.setOnClickListener {
            val position = et_position.text.toString().trim()
            if (position.isNotEmpty()){
                val index = position.toInt()
                if (index < 0 || index >= mLayoutNames.size) {
                    ToastUtils.show("index scope [0, ${mLayoutNames.size - 1}]")
                } else {
                    delList.add(index) // index
                    SPUtils.getInstance().put("layout_test", listToString(delList))
                    showDescAndRefresh(delList)
                    et_position.setText("")
                }
            }
        }

        //(index)
        bt_add.setOnClickListener {
            val position = et_position.text.toString().trim()
            if (position.isNotEmpty()){
                val index = position.toInt()
                if (index < 0 || index >= mLayoutNames.size) {
                    ToastUtils.show("index scope [0, ${mLayoutNames.size - 1}]")
                } else {
                    delList.remove(index) // index
                    SPUtils.getInstance().put("layout_test", listToString(delList))
                    showDescAndRefresh(delList)
                    et_position.setText("")
                }
            }
        }

        //(index)
        bt_clear.setOnClickListener {
            delList.clear()
            SPUtils.getInstance().put("layout_test", "")
            showDescAndRefresh(delList)
            et_position.setText("")
        }
    }

    // TODO 看这里
    private fun initLayoutNames():ArrayList<String>{
        val list = ArrayList<String>()
        list.add("act_demo")
        list.add("act_layout_test")
        list.add("act_main")
        return list
    }

    private fun listToString(list: LinkedHashSet<Int>): String {
        val builder = StringBuilder()
        if (list.isNotEmpty()) {
            for (v in list) {
                builder.append(v).append(",")
            }
            builder.delete(builder.length - 1, builder.length)
        }
        return builder.toString()
    }

    private fun showDescAndRefresh(list: LinkedHashSet<Int>) {
        tv_del_desc.text = ""
        mDelList.clear()
        if (list.isNotEmpty()) {
            for (v in list) { // index
                val layoutName = mLayoutNames[v]
                mDelList.add(layoutName)
                tv_del_desc.text = "${tv_del_desc.text}${layoutName}($v), "
            }
        }

        refreshData()
    }

    private val mDelList = ArrayList<String>()
    private fun refreshData(){
        mAdapter.data.clear()
        for ((index, name) in mLayoutNames.withIndex()) {
            if (mDelList.contains(name)) {
                continue
            }
            mAdapter.data.add(LayoutTestData(R.layout.item_layout_test, "$name(${index})"))
            mAdapter.data.add(LayoutTestData(layoutNameById(name)))
        }
        mAdapter.notifyDataSetChanged()
    }

    private lateinit var mLayoutNames: ArrayList<String>
    private lateinit var mAdapter: LayoutTestAdapter
    private fun initRecyclerView(){
        mLayoutNames = initLayoutNames()
        rv_content.layoutManager = LinearLayoutManager(this)
        mAdapter = LayoutTestAdapter()
        rv_content.adapter = mAdapter
    }

    private fun layoutNameById(layoutName: String):Int{
        return resources.getIdentifier(layoutName, "layout", packageName)
    }

    data class LayoutTestData(
        val layoutId: Int, // viewType
        val layoutName: String? = null // title
    )

    class LayoutTestAdapter : RBaseAdapter<LayoutTestData>(){

        override fun onCreateRViewHolder(parent: ViewGroup?, viewType: Int): RViewHolder {
            // 处理 merge 标签
            val fl = RelativeLayout(parent!!.context)
            val view = LayoutInflater.from(parent.context).inflate(viewType, fl, true)
            view.layoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                DisplayUtil.dp2px(480F)
            )
            return RViewHolder(fl)
        }

        override fun onBindRViewHolder(holder: RViewHolder?, position: Int, viewType: Int) {
            mList[position].layoutName?.let {
                holder?.setText<TextView>(R.id.tv_title, "$it pos ${position / 2}")
            }
        }

        override fun getItemViewType(position: Int): Int {
            return mList[position].layoutId
        }
    }
}